package l1j.opqlo.Timer.Controler;

import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.WorldItemEnchantTime;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_OwnCharStatus;
import l1j.server.server.serverpackets.S_ServerMessage;

public class EnchantTimer extends TimerTask {

	private static final Logger _log = Logger.getLogger(EnchantTimer.class
			.getName());

	private ScheduledFuture<?> _timer;

	private void End(final L1ItemInstance item) {
		item.setAcByMagic(0);
		item.setDmgByMagic(0);
		item.setHolyDmgByMagic(0);
		item.setHitByMagic(0);
		WorldItemEnchantTime.get().remove(item.getId());
		item._isRunning = false;
	}

	@Override
	public void run() {
		try {
			final Collection<L1ItemInstance> items = WorldItemEnchantTime.get()
					.all();

			// 不包含元素
			if (items.isEmpty()) {
				return;
			}
			for (final L1ItemInstance _item : items) {
				final int time = _item.getSkillTime();
				if (time - 5 > 0) {
					_item.addSkillTime(-5);
					// System.out.println(_item.getSkillTime() +" / "+
					// _item.getName());
					continue;
				}

				_item.addSkillTime(-time);

				final L1PcInstance _pc = _item.getItemMaster();

				if (_pc == null) {
					_log.log(Level.WARNING,
							"EnchantTimer[PC為空]: " + _item.getName() + "流水編號:"
									+ _item.getId() + "計時錯誤。");
					this.End(_item);
					Thread.sleep(5);
					continue;
				}
				final int itemId = _item.getItem().getItemId();

				if (!_pc.getInventory().checkItem(itemId)) {
					_log.log(Level.WARNING,
							"EnchantTimer[不在背包]: " + _item.getName() + "流水編號:"
									+ _item.getId() + "計時錯誤。");
					this.End(_item);
					Thread.sleep(5);
					continue;
				}

				final int type = _item.getItem().getType();
				final int type2 = _item.getItem().getType2();
				if (type == 2 && type2 == 2 && _item.isEquipped()) {
					_pc.addAc(3);
					_pc.sendPackets(new S_OwnCharStatus(_pc));
				}
				_pc.sendPackets(new S_ServerMessage(308, _item.getLogName()));
				this.End(_item);
				Thread.sleep(5);
			}
		} catch (final Exception e) {
			PcOtherThreadPool.get().cancel(this._timer, false);
			final EnchantTimer useTime = new EnchantTimer();
			useTime.start();
			_log.log(Level.WARNING, "EnchantTimer: 計時時間軸異常重啟");
		}
	}

	public void start() {
		final int timeMillis = 5000;// 5秒
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this,timeMillis, timeMillis);
	}
}
